// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html


let Input = {};  //用来存放按键的按键码
cc.Class({
    extends: cc.Component, 

    properties: {
        
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        //监听键盘按键事件
        cc.systemEvent.on("keydown", this.onKeyDown, this);
        cc.systemEvent.on("keyup", this.onKeyUp, this);

        this._speed = 180;
        this.state =  "";
        this.sp = cc.v2(0,0);
        this.heroAni = this.node.getComponent(cc.Animation);

        this.lv = this.node.getComponent(cc.RigidBody).linearVelocity; // 获取当前组件的线性速度
    

    },


    setState(state){
        if(this.state == state) return false;

        this.state = state;
        this.heroAni.play(state);  //执行动画
    },



    onKeyDown(e ){
        Input[e.keyCode] = 1 ;
    },

    onKeyUp(e){
        Input[e.keyCode] = 0 ;
    },


    start () {

    },

    update (dt) {

        if(window.dialog && window.dialog.active) return ;  //这个是防止对话时玩家移动

        let s = this._speed * dt;  // 运动的路程
        if(Input[cc.macro.KEY.a] || Input[cc.macro.KEY.left]){
            this.sp.x = -1;
        }else if(Input[cc.macro.KEY.d] || Input[cc.macro.KEY.right]){
            this.sp.x = 1; 
        }else if(Input[cc.macro.KEY.w] || Input[cc.macro.KEY.up]){
            this.sp.y = 1;
        }else if(Input[cc.macro.KEY.s] || Input[cc.macro.KEY.down]){
            this.sp.y = -1;
        }else{
            this.sp.x = 0;
            this.sp.y = 0;
        }

            // this.node.getComponent(cc.RigidBody).linearVelocity = this.lv;
        if(this.sp.x){
            this.lv.y = 0 ;
            this.lv.x = this.sp.x * this._speed;
        }else if(this.sp.y){
            this.lv.x = 0 ;
            this.lv.y = this.sp.y * this._speed;
        }else{
            this.lv.x = 0 ;
            this.lv.y = 0 ;
        }

        this.node.getComponent(cc.RigidBody).linearVelocity = this.lv;

        

        let state = ""; 
        if(this.sp.x == -1){
            state = "hero_left";
        }else if(this.sp.x == 1){
            state = "hero_right"; 
        }else if(this.sp.y == -1){
            state = "hero_down";
        }else if(this.sp.y == 1){
            state = "hero_up"; 
        }
        if(state){
            this.setState(state);
        }
        
    },

});
